# -*- coding: utf-8 -*-            
# @Author : HJH
# @Time : 2024/3/1 13:45
# @Use :
import hashlib
import json
import time

import requests
from loguru import logger


def send_request(mobile, checkCode=None):
    appkey = "B20230907024"
    secret = "NoPt5JpRfRU6d4pR75Mz8nWdLQafhGbR"
    # appkey = "B20230916027"
    # secret = "fBhMoEhoXNfKJ2SMBkekrc2RK4xT6zzn"
    url = "http://openapi.tenfli.com/extra/account/sms-login"
    req = {"mobile": mobile, "supplier": "LyApp", "checkCode": checkCode}

    # 签名生成
    time_millis = int(time.time() * 1000)
    text = f"{appkey}&{time_millis}&{secret}"
    sign = hashlib.md5(text.encode('utf-8')).hexdigest()

    # 构建请求
    headers = {
        "Content-Type": "application/json",
        "appKey": appkey,
        "sign": sign,
        "timestamp": str(time_millis)
    }

    """
    请求接口
    """
    response = requests.post(url, headers=headers, json=req)
    result = response.text
    try:
        res_data = json.loads(result)
        return res_data
    except (requests.exceptions.RequestException, json.JSONDecodeError) as e:
        print(e)
        return None


def send_verification_code(vc_phone):
    while True:
        code = input("输入接收到的验证码: ")
        res = send_request(vc_phone, code)
        status = res['status']
        if status == 'SUCCESS':
            print(f'【配置成功】: {res["status"]}')
            print(f"配置手机号 {vc_phone} 成功。")
            break
        else:
            print(f'【配置出错】: {res["errorMsg"]}')
            if "请重新输入" in res["errorMsg"]:
                continue
            else:
                break


if __name__ == '__main__':
    print("***************** 欢迎使用同程手机号验证码登录系统 *****************")

    while True:
        print("开始配置手机号... ...")
        phone = input("输入需要配置的手机号: ")
        res_once = send_request(phone)
        if res_once['status'] != 'SUCCESS':
            print(f'【发送验证码失败】: {res_once["errorMsg"]}，请重试')
            continue
        print(f'【发送验证码成功】: {res_once["status"]}')

        send_verification_code(phone)
        print(f'【配置成功】: SUCCESS')
        print(f"配置手机号{phone}成功。")

        time.sleep(1)

        print("... ...")
        print("... ...")
        print("... ...")
